/*
 *
 * Copyright (C) 2012 Mauricio Garcia
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "gstreamerUtils.h"

gboolean bus_call(GstBus *bus, GstMessage *msg, gpointer data){

  GMainLoop *loop = (GMainLoop *) data;

  switch (GST_MESSAGE_TYPE (msg)) {

    case GST_MESSAGE_EOS:
      g_print ("End of stream\n");
      g_main_loop_quit (loop);
      break;

    case GST_MESSAGE_ERROR: {
      gchar  *debug;
      GError *error;

      gst_message_parse_error (msg, &error, &debug);
      g_free (debug);

      g_printerr ("Error: %s\n", error->message);
      g_error_free (error);

      g_main_loop_quit (loop);
      break;
    }
    default:
      break;
  }

  return TRUE;
}

GstElement * recvVoicePipeline(int port){

  GstElement *pipeline, *source, *filter, *extractor, *conv, *sink;
  
  /* Create gstreamer elements */
  pipeline = gst_pipeline_new ("audio-server");
  source   = gst_element_factory_make ("udpsrc",       "udp-server-input");
  filter 	 = gst_element_factory_make ("capsfilter", "filter");
  extractor  = gst_element_factory_make ("rtpL16depay",     "raw-audio-extractor");
  conv     = gst_element_factory_make ("audioconvert",  "converter");
  sink     = gst_element_factory_make ("alsasink", "audio-output");
  
  if (!pipeline || !source || !filter || !extractor || !conv || !sink) {
    g_printerr ("One element could not be created. Exiting.\n");
    return NULL;
  }
  
  /* Set up the pipeline */
  
  /* we set the input filename to the source element */
  g_object_set (G_OBJECT (source), "port", port, NULL);
  
  /* Se the capabilities of the src pad of the udpsrc element*/
  GstCaps *filterCaps;
  filterCaps = gst_caps_new_simple ("application/x-rtp",
				    "media", G_TYPE_STRING, "audio",
				    "clock-rate",G_TYPE_INT, 44100,
				    "width", G_TYPE_INT, 16,
				    "height", G_TYPE_INT, 16,
				    "encoding-name", G_TYPE_STRING,"L16",
				    "encoding-params",G_TYPE_STRING,"1",
				    "channels",G_TYPE_INT,1,
				    "channel-positions",G_TYPE_INT,1,
				    "payload",G_TYPE_INT,96,
				    NULL);
  
  g_object_set (G_OBJECT (filter), "caps", filterCaps, NULL);
  gst_caps_unref (filterCaps);
  
  g_object_set (G_OBJECT (sink), "sync", 0, NULL);
  
  /* we add all elements into the pipeline */
  gst_bin_add_many (GST_BIN (pipeline),
                    source, filter, extractor, conv, sink, NULL);
  
  /* we link the elements together */
  gst_element_link_many (source, filter, extractor, conv, sink, NULL);
  
  return pipeline;
  
}

GstElement * sendVoicePipeline(const char* host, int port){
  
  GstElement *pipeline, *source, *conv, *filter, *packer, *sink;
  
  /* Create gstreamer elements */
  pipeline = gst_pipeline_new ("audio-client");
  source   = gst_element_factory_make ("alsasrc",       "microphone-source");
  conv     = gst_element_factory_make ("audioconvert",  "converter");
  filter   = gst_element_factory_make ("capsfilter", "filter");
  packer   = gst_element_factory_make ("rtpL16pay",      "packer-rtp");
  sink     = gst_element_factory_make ("udpsink", "udp-client-output");
  
  if (!pipeline || !source || !conv || !filter || !packer || !sink) {
    g_printerr ("One element could not be created. Exiting.\n");
    return NULL;
  }
  
  /* Set up the pipeline */
  
  /* Se the capabilities of the src pad of the alsasrc element*/
  
  GstCaps *filterCaps;
  filterCaps = gst_caps_new_simple ("audio/x-raw-int",
				    "channels",G_TYPE_INT,1,
				    "depth", G_TYPE_INT, 16,
				    "width", G_TYPE_INT, 16,
				    "rate", G_TYPE_INT, 44100,
				    NULL);
  
  g_object_set (G_OBJECT (filter), "caps", filterCaps, NULL);
  gst_caps_unref (filterCaps);
  
  /* we set the input filename to the source element */
  g_object_set (G_OBJECT (sink), "host", host, NULL);
  g_object_set (G_OBJECT (sink), "port", port, NULL);
  
  /* we add all elements into the pipeline */
  gst_bin_add_many (GST_BIN (pipeline),
                    source, conv, filter, packer, sink, NULL);
  
  /* we link the elements together */
  gst_element_link_many (source, conv, filter, packer, sink, NULL);
  
  return pipeline;
}

int playStream(int localPort, const char *peerHost, int peerPort){

 	/* Initialisation of gstreamer*/
  gst_init (NULL, NULL);

  GMainLoop *loop;

  GstElement *pipelineSend, *pipelineRecv;
  GstBus *busSend, *busRecv;

  loop = g_main_loop_new (NULL, FALSE);

  pipelineRecv = recvVoicePipeline(localPort);
  pipelineSend = sendVoicePipeline(peerHost, peerPort);
  
	/* we add a message handler */
  busSend = gst_pipeline_get_bus (GST_PIPELINE (pipelineSend));
  gst_bus_add_watch (busSend, bus_call, loop);
  gst_object_unref (busSend);

  busRecv = gst_pipeline_get_bus (GST_PIPELINE (pipelineRecv));
  gst_bus_add_watch (busRecv, bus_call, loop);
  gst_object_unref (busRecv);

  /* Set the pipeline to "playing" state*/
  g_print ("Sending and receiving stream\n");
  gst_element_set_state (pipelineSend, GST_STATE_PLAYING);
  gst_element_set_state (pipelineRecv, GST_STATE_PLAYING);
	
  /* Iterate */
  g_print ("Running...\n");
  g_main_loop_run (loop);

  /* Out of the main loop, clean up nicely */
  g_print ("Returned, stopping playback\n");
  gst_element_set_state (pipelineSend, GST_STATE_NULL);
  gst_element_set_state (pipelineRecv, GST_STATE_NULL);

  g_print ("Deleting pipeline\n");
  gst_object_unref (GST_OBJECT (pipelineSend));
  gst_object_unref (GST_OBJECT (pipelineRecv));

  return 0;
}
